package com.sales.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 2025/11/3 15:51
 * author: 向远洋
 * 结合分布式锁，高并发环境下，用户获取当前订单唯一编号
 */
@Component
public class UniqueOrderCode {
    @Autowired
    RedisUtil redisUtil;
    public String getCode(String companyCode, String type) throws InterruptedException {
        String lockKey = "lock:" + companyCode + ":" + type;
        boolean isLocked = false; // 标志位：是否已获得锁
        try {
            do {
                isLocked = redisUtil.tryLock(lockKey, 10); //最多持有锁10s
                if (isLocked) {
                    //获取到锁后，生成当担的编号
                    String key = companyCode + ":" + type;
                    String value = redisUtil.getStr(key);
                    // 添加空值检查
                    if (value == null || value.trim().isEmpty()) {
                        value = "1"; // 如果值不存在，初始化为1
                    }
                    Integer digit = Integer.parseInt(value); //预估一天内该公司xxx订单最多不超过10000，即展示四位数
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    String code = sdf.format(new Date());
                    code += String.format("%04d", digit);
                    digit++;
                    redisUtil.setStr(key, digit.toString());
                    return code;
                } else {
                    Thread.sleep(20);
                }
            } while (true);
        }finally {
            //持有锁才释放锁
            if(isLocked) redisUtil.releaseLock(lockKey);
        }
    }
}
